<?php

namespace App\Http\Controllers\Api;

use App\User;
use App\Models\Order;
use App\Models\Product;
use App\Models\Password;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Cache;

class ApiController extends Controller
{
    public function login(Request $request)
    {

        $user = User::where('username', $request->username)->first();
        if (!isset($user)) {
            return error('Account or password error, login failed');
        }
        $pwd = Password::where('password', $request->password)->first();
        if (!isset($pwd)) {
            return error('Account or password error, login failed');
        }
        $token = Str::random(32);
        Cache::put($token, $user, 60 * 60 * 2);
        return success($token);
    }

    public function products()
    {
        $products = Product::where('is_up', 1)->get();
        foreach ($products as &$product) {
            $images = $product->image;
            foreach($images as &$image) {
                $image = env('QINIU_DOMAIN_HTTP') . '/' . $image . imageWatermark('YUTA');
            }
            $product->image = $images;
        }
        return success($products);
    }

    public function storeOrder(Request $request)
    {
        $user = $this->user();
        $products =  json_encode($request->products);
        $order = Order::create([
            'order_no' => getOrderNo(),
            'user_id' => $user['id'],
            'product' => $products,
        ]);
        if ($order) {
            return success();
        }
        return error();
    }

    public function orders(Request $request)
    {
        $user = $this->user();
        $orders = Order::where('user_id', $user['id'])->orderBy('id', 'desc')->get();
        if ($orders) {
            foreach($orders as &$order) {
                $products = $order->product;
                foreach($products as &$product) {
                    $product = Product::find($product, ['id', 'name','image']);
                    $images = $product->image;
                    foreach($images as &$image) {
                        $image = env('QINIU_DOMAIN_HTTP') . '/' . $image . imageWatermark('YUTA');
                    }
                    $product->image = $images;
                }
                $order->products = $products;
            }
            return success($orders);
        }
        return error();
    }
}
